package com.aitaoxue.palx.fragment;

import io.rong.imkit.RongIM;

import java.io.File;
import java.util.Set;

import org.apache.http.Header;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseFragment;
import com.aitaoxue.palx.bean.IndexInfo;
import com.aitaoxue.palx.ui.AboutActivity;
import com.aitaoxue.palx.ui.MyCourseActivity;
import com.aitaoxue.palx.ui.register.ForgetPasswordActivity2;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.util.ImageUtil;
import com.aitaoxue.palx.widget.CircleImageView;
import com.aitaoxue.palx.widget.ProgressView;
import com.aitaoxue.palx.widget.RevealLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class AiTaoXueFragment extends BaseFragment {

	private static final String TAG = AiTaoXueFragment.class.getSimpleName();

	@InjectView(R.id.header)
	CircleImageView header;
	@InjectView(R.id.name)
	TextView name;
	@InjectView(R.id.username)
	TextView username;
	@InjectView(R.id.progress)
	ProgressView progressView;

	@InjectView(R.id.course_layout)
	RelativeLayout courseLayout;
	@InjectView(R.id.password_layout)
	RelativeLayout passwordLayout;
	@InjectView(R.id.about_layout)
	RelativeLayout aboutLayout;
	@InjectView(R.id.quit_layout)
	RelativeLayout quitLayout;
	@InjectView(R.id.new_icon)
	TextView newIcon;

	private View view;

	// 相机
	private static final int REQUEST_CAMERA = 1;
	// 相册截图
	private static final int REQUEST_CHOOSE = 2;
	// 截取
	private static final int REQUEST_CROP = 3;

	private Uri originalName;
	private String imagePath;
	private String cropPath;

	private Bitmap bitmap;

	private PopupWindow window;

	private ProgressDialog progressDialog;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_aitaoxue, container, false);

		ButterKnife.inject(this, view);

		initView(view);

		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initData();
	}

	@Override
	public void onResume() {
		super.onResume();
		String newVersion = AppContext.getInstance().getProperty("new_version");
		if (newVersion != null && newVersion.equals("true")) {
			newIcon.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.header:
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			View popView = inflater.inflate(R.layout.popup_window_header, null);
			window = new PopupWindow(getActivity());
			window.setContentView(popView);
			window.setWidth(LayoutParams.MATCH_PARENT);
			window.setHeight(LayoutParams.WRAP_CONTENT);
			window.setFocusable(true);
			window.setAnimationStyle(R.anim.footer_menu_slide_in);
			window.setBackgroundDrawable(new ColorDrawable(0x123456));
			window.setOutsideTouchable(true);
			RevealLayout left = (RevealLayout) popView.findViewById(R.id.left);
			RevealLayout right = (RevealLayout) popView
					.findViewById(R.id.right);

			setAlpha();

			left.setOnClickListener(this);

			right.setOnClickListener(this);

			window.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					removeAlpha();
				}
			});

			window.showAtLocation(view, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.left:
			// 拍照
			Intent takePictureIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			File file = ImageUtil.getImagePath();
			imagePath = file.getAbsolutePath();
			originalName = Uri.fromFile(file);
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, originalName);

			startActivityForResult(takePictureIntent, REQUEST_CAMERA);
			break;
		case R.id.right:
			// 从相册选择
			Intent intent = new Intent(Intent.ACTION_PICK, null);
			intent.setType("image/*");
			intent.putExtra("crop", "false");
			intent.putExtra("return-data", false);
			File file2 = ImageUtil.getImagePath();
			imagePath = file2.getAbsolutePath();
			originalName = Uri.fromFile(file2);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, originalName);
			intent.putExtra("outputFormat",
					Bitmap.CompressFormat.JPEG.toString());
			intent.putExtra("noFaceDetection", true); // no face detection
			startActivityForResult(intent, REQUEST_CHOOSE);
			break;
		case R.id.course_layout:
			startActivity(new Intent(getActivity(), MyCourseActivity.class));
			break;
		case R.id.password_layout:
			Intent intent2 = new Intent(getActivity(),
					ForgetPasswordActivity2.class);
			intent2.putExtra("from", "fragment");
			startActivity(intent2);
			break;
		case R.id.about_layout:
			startActivity(new Intent(getActivity(), AboutActivity.class));
			break;
		case R.id.quit_layout:
			AlertDialog dialog = new AlertDialog.Builder(getActivity())
					.setMessage("确定退出登录吗?")
					.setPositiveButton("确定", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							if (progressDialog == null) {
								progressDialog = new ProgressDialog(
										getActivity());
								progressDialog.setMessage("退出登录中...");
							}
							progressDialog.show();
							quit();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).create();
			dialog.show();
			break;
		default:
			break;
		}
	}

	@Override
	public void initView(View view) {
		AitaoXueApi.getProdInfoIndex(mHandler);

		header.setOnClickListener(this);
		courseLayout.setOnClickListener(this);
		passwordLayout.setOnClickListener(this);
		aboutLayout.setOnClickListener(this);
		quitLayout.setOnClickListener(this);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CAMERA:
			File tmpFile = new File(imagePath);
			if (tmpFile.length() == 0) {
				tmpFile.delete();
				return;
			}
			// 拍照结束
			cropImageUri(originalName);
			break;
		case REQUEST_CHOOSE:
			File tmpFile2 = new File(imagePath);
			if (tmpFile2.length() == 0) {
				tmpFile2.delete();
				return;
			}
			// 压缩
			bitmap = ImageUtil.compressImgFromFile(imagePath, 150f, 150f);
			ImageUtil.compressBitmapToFile(imagePath, bitmap, 30);
			window.dismiss();
			progressView.setVisibility(View.VISIBLE);
			// 上传
			AitaoXueApi.UploadHeader(new File(imagePath), mTestHandler);

			ImageLoader.getInstance().displayImage("file:///" + imagePath,
					header);
			break;
		// 截取
		case REQUEST_CROP:
			// 截取成功,进行压缩
			bitmap = ImageUtil.compressImgFromFile(cropPath, 150f, 150f);

			ImageUtil.compressBitmapToFile(cropPath, bitmap, 30);

			File file = new File(imagePath);
			file.delete();

			window.dismiss();
			progressView.setVisibility(View.VISIBLE);
			// 上传
			AitaoXueApi.UploadHeader(new File(cropPath), mTestHandler);

			ImageLoader.getInstance().displayImage("file:///" + cropPath,
					header);
			break;
		default:
			break;
		}
	}

	@Override
	public void initData() {

	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			IndexInfo info = GsonUtil.GsonToBean(res, IndexInfo.class);

			name.setText(info.getContent().getProd_name());
			username.setText("帐号:" + info.getContent().getProd_phone());

			ImageLoader.getInstance().displayImage(
					ApiHttpClient.HEADER_PREFIX
							+ info.getContent().getProd_head_thumb(), header);
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			System.out.println("here");
		}
	};

	private AsyncHttpResponseHandler mTestHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);
			Toast.makeText(getActivity(), "上传成功:", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Toast.makeText(getActivity(), "上传失败,请重新上传", Toast.LENGTH_SHORT)
					.show();
		}

		public void onProgress(int bytesWritten, int totalSize) {
			int progress = (int) (((float) bytesWritten / totalSize) * 100);
			progressView.setProgress(progress > 100 ? 100 : progress);

			if (progress >= 100 && progressView.getVisibility() == View.VISIBLE) {
				progressView.setVisibility(View.GONE);
			}
		}

	};

	// 将屏幕加一层透明度
	private void setAlpha() {
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 0.5f;

		getActivity().getWindow().setAttributes(lp);
	}

	// 去掉屏幕的透明度
	private void removeAlpha() {
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 1.0f;

		getActivity().getWindow().setAttributes(lp);
	}

	private void cropImageUri(Uri uri) {
		File file = ImageUtil.getImagePath();
		cropPath = file.getAbsolutePath();
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("scale", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

		startActivityForResult(intent, REQUEST_CROP);
	}

	private void quit() {
		// 清除登录标志
		AppContext.getInstance().removeProperty("user.username",
				"user.password", "user.token", "user.city");
		AppContext.getInstance().setProperty("setalias", "no");
		// 退出融云
		RongIM.getInstance().disconnect();
		// 极光设置别名0000
		JPushInterface.setAlias(getActivity(), "0000", new TagAliasCallback() {

			@Override
			public void gotResult(int arg0, String arg1, Set<String> arg2) {
				progressDialog.dismiss();
				android.os.Process.killProcess(android.os.Process.myPid());
				System.exit(0);
			}
		});
	}
}
